package br.edu.ufcg.embedded.eolica.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;


public class Properties { //implements ConfigIF {

	private static Properties instance = null;
	String defLang;
	Vector data;
	String lang;

	private Properties() {
		lang = null;
		String value = System.getProperty("microedition.locale");
		if (value != null) {
			// uses the 'value' length for the device default language
			lang = value.substring(0, value.length()).trim();
		}
	}

	/**
	 * Get the instance of the propertie object
	 * 
	 * @return the instance
	 */
	public static Properties getInstance() {
		if (instance == null) {
			instance = new Properties();
		}
		return instance;
	}

	public String getLang() {
		return lang;
	}

	public void setDefLang(String defLang) {
		this.defLang = defLang;
	}

	public void load(String resource) {
		InputStreamReader r = getInputStream(resource);

		char[] buffer = new char[32];
		StringBuffer sb = new StringBuffer();
		int count;
		try {
			while ((count = r.read(buffer, 0, buffer.length)) > -1) {
				sb.append(buffer, 0, count);
			}
			data = TextUtils.split(sb.toString(), '=');
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Loads the language file to the configuration
	 * 
	 * @param resource
	 *            the file
	 * @return an InputStreamReader
	 */
	private InputStreamReader getInputStream(String resource) {
		InputStream is;
		try {
			is = getClass().getResourceAsStream("/" + lang + resource.trim());
			return new InputStreamReader(is);
		} catch (NullPointerException n) {
			try {
				is = getClass().getResourceAsStream(
						"/" + lang.substring(0, defLang.length()).trim()
								+ resource.trim());
				return new InputStreamReader(is);
			} catch (NullPointerException e) {
			} catch (StringIndexOutOfBoundsException s) {
			}
			try {
				is = getClass().getResourceAsStream(
						"/" + defLang + resource.trim());
				return new InputStreamReader(is);
			} catch (NullPointerException e) {
				is = getClass().getResourceAsStream("/" + resource.trim());
				return new InputStreamReader(is);
			}
		}
	}

	public Vector getData() {
		return data;
	}

	public String getProperty(String key) {
		DataProperties dataProp;
		int size = data.size();
		for (int i = 0; i < size; i++) {
			dataProp = (DataProperties) data.elementAt(i);
			if (dataProp.getKey().equals(key.toLowerCase())) {
				return dataProp.getValue();
			}
		}
		return key;
	}
}
